#include "mainwindow.h"
#if 0
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}
#endif
#if 0
#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
#include <algorithm>
#include <random>
#include <climits>
#include <ctime>

// 音频参数
const int SAMPLE_RATE = 16000;   // 16kHz
const int BIT_DEPTH = 16;        // 16-bit
const int DURATION = 10;         // 10秒
const int NUM_SAMPLES = SAMPLE_RATE * DURATION;

// 音频数据容器
using AudioData = std::vector<int16_t>;

// 生成基本正弦波
void generateSineWave(AudioData& data, double freq, double amplitude = 0.8) {
    for (int i = 0; i < data.size(); i++) {
        double t = static_cast<double>(i) / SAMPLE_RATE;
        double value = amplitude * (1 << (BIT_DEPTH - 1)) * std::sin(2.0 * M_PI * freq * t);
        data[i] = static_cast<int16_t>(value);
    }
}

// 生成扫频信号 (20Hz - 8kHz)
void generateSweep(AudioData& data) {
    const double startFreq = 20.0;
    const double endFreq = 8000.0;

    for (int i = 0; i < data.size(); i++) {
        double t = static_cast<double>(i) / SAMPLE_RATE;
        double freq = startFreq + (endFreq - startFreq) * (t / DURATION);
        double value = 0.8 * (1 << (BIT_DEPTH - 1)) * std::sin(2.0 * M_PI * freq * t);
        data[i] = static_cast<int16_t>(value);
    }
}

// 添加中断 (静音段)
void addInterruption(AudioData& data, int startSample, int durationSamples) {
    std::fill(data.begin() + startSample,
              data.begin() + startSample + durationSamples, 0);
}

// 添加回声
void addEcho(AudioData& data, int delaySamples, double decay) {
    for (int i = data.size() - 1; i >= delaySamples; i--) {
        double value = data[i] + decay * data[i - delaySamples];

        // 防止溢出
        if (value > SHRT_MAX) value = SHRT_MAX;
        else if (value < SHRT_MIN) value = SHRT_MIN;

        data[i] = static_cast<int16_t>(value);
    }
}

// 添加断续 (随机静音段)
void addChoppiness(AudioData& data, int segmentLength = 80) {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<int> dist(0, data.size() - segmentLength);

    // 添加10个静音段
    for (int i = 0; i < 10; i++) {
        int pos = dist(gen);
        std::fill(data.begin() + pos, data.begin() + pos + segmentLength, 0);
    }
}

// 添加杂音 (随机噪声)
void addNoise(AudioData& data, double noiseLevel) {
    std::random_device rd;
    std::mt19937 gen(rd());
    int16_t maxNoise = static_cast<int16_t>(noiseLevel * (1 << (BIT_DEPTH - 1)));
    std::uniform_int_distribution<int16_t> dist(-maxNoise, maxNoise);

    for (int i = 0; i < data.size(); i++) {
        int32_t value = static_cast<int32_t>(data[i]) + dist(gen);

        // 防止溢出
        if (value > SHRT_MAX) value = SHRT_MAX;
        else if (value < SHRT_MIN) value = SHRT_MIN;

        data[i] = static_cast<int16_t>(value);
    }
}

// 保存为WAV文件
void saveAsWav(const std::string& filename, const AudioData& data) {
    std::ofstream file(filename, std::ios::binary);

    // WAV文件头
    struct WavHeader {
        char riff[4] = {'R', 'I', 'F', 'F'};
        uint32_t chunkSize;
        char wave[4] = {'W', 'A', 'V', 'E'};
        char fmt[4] = {'f', 'm', 't', ' '};
        uint32_t fmtSize = 16;
        uint16_t audioFormat = 1; // PCM
        uint16_t numChannels = 1;
        uint32_t sampleRate;
        uint32_t byteRate;
        uint16_t blockAlign;
        uint16_t bitsPerSample;
        char data[4] = {'d', 'a', 't', 'a'};
        uint32_t dataSize;
    };

    WavHeader header;
    header.chunkSize = 36 + data.size() * sizeof(int16_t);
    header.sampleRate = SAMPLE_RATE;
    header.byteRate = SAMPLE_RATE * sizeof(int16_t);
    header.blockAlign = sizeof(int16_t);
    header.bitsPerSample = BIT_DEPTH;
    header.dataSize = data.size() * sizeof(int16_t);

    file.write(reinterpret_cast<const char*>(&header), sizeof(header));
    file.write(reinterpret_cast<const char*>(data.data()), data.size() * sizeof(int16_t));
}

// 计算信号能量
double calculateEnergy(const AudioData& data, int start, int end) {
    double energy = 0.0;
    int count = 0;
    for (int i = start; i < end && i < data.size(); i++) {
        double sample = static_cast<double>(data[i]) / (1 << (BIT_DEPTH - 1));
        energy += sample * sample;
        count++;
    }
    return count > 0 ? energy / count : 0.0;
}

// 检测中断 (静音段) - 已优化
bool detectInterruption(const AudioData& data, double threshold = 0.01) {
    const int windowSize = 512; // 32ms窗口
    const int silenceThreshold = 10; // 需要连续10个窗口静音

    int silentWindows = 0;
    for (int i = 0; i < data.size(); i += windowSize) {
        double energy = calculateEnergy(data, i, i + windowSize);

        if (energy < threshold) {
            silentWindows++;
            if (silentWindows >= silenceThreshold) {
                return true;
            }
        } else {
            silentWindows = 0;
        }
    }
    return false;
}

// 检测回声 (使用自相关) - 优化版本
bool detectEcho(const AudioData& data) {
    const int windowSize = 1024; // 64ms窗口
    const int minDelay = 100;    // 6.25ms
    const int maxDelay = 2000;   // 125ms
    const double threshold = 0.15; // 降低阈值

    // 选择分析区域（避免扫频信号变化过快的区域）
    int start = SAMPLE_RATE * 2; // 2秒处开始
    int end = std::min(start + windowSize * 10, static_cast<int>(data.size()) - maxDelay);

    for (; start < end; start += windowSize) {
        // 计算自相关
        std::vector<double> correlations(maxDelay - minDelay, 0.0);
        for (int delay = minDelay; delay < maxDelay; delay++) {
            double sum = 0.0;
            int count = 0;

            for (int i = start; i < start + windowSize; i++) {
                double sample1 = static_cast<double>(data[i]) / (1 << (BIT_DEPTH - 1));
                double sample2 = static_cast<double>(data[i + delay]) / (1 << (BIT_DEPTH - 1));
                sum += sample1 * sample2;
                count++;
            }

            if (count > 0) {
                correlations[delay - minDelay] = sum / count;
            }
        }

        // 寻找显著峰值
        double maxCorr = *std::max_element(correlations.begin(), correlations.end());
        if (maxCorr > threshold) {
            // 检查峰值是否明显高于平均值
            double sum = std::accumulate(correlations.begin(), correlations.end(), 0.0);
            double avg = sum / correlations.size();

            if (maxCorr > 3.0 * avg) {
                return true;
            }
        }
    }
    return false;
}

// 检测断续 - 优化版本
bool detectChoppiness(const AudioData& data) {
    const int windowSize = 160; // 10ms窗口
    const double energyThreshold = 0.02;
    const double silenceRatioThreshold = 0.1; // 10%的静音窗口

    int silentCount = 0;
    int totalWindows = 0;

    for (int i = 0; i < data.size(); i += windowSize) {
        double energy = calculateEnergy(data, i, i + windowSize);

        if (energy < energyThreshold) {
            silentCount++;
        }
        totalWindows++;
    }

    double silentRatio = static_cast<double>(silentCount) / totalWindows;
    return silentRatio > silenceRatioThreshold;
}

// 检测杂音 - 优化版本
bool detectNoise(const AudioData& data) {
    // 计算整体信噪比
    double totalEnergy = 0.0;
    double minEnergy = 1.0;
    double maxEnergy = 0.0;

    const int windowSize = 512;
    std::vector<double> energies;

    for (int i = 0; i < data.size(); i += windowSize) {
        double energy = calculateEnergy(data, i, i + windowSize);
        energies.push_back(energy);
        totalEnergy += energy;

        if (energy < minEnergy) minEnergy = energy;
        if (energy > maxEnergy) maxEnergy = energy;
    }

    // 计算动态范围
    double dynamicRange = 10 * log10(maxEnergy / (minEnergy + 1e-10));

    // 计算低能量窗口比例
    double lowEnergyCount = 0;
    double lowEnergyThreshold = totalEnergy / energies.size() * 0.1; // 平均能量的10%
    for (double e : energies) {
        if (e < lowEnergyThreshold) {
            lowEnergyCount++;
        }
    }
    double lowEnergyRatio = lowEnergyCount / energies.size();

    // 动态范围 < 40dB 或 低能量窗口占比 > 20% 视为有杂音
    return dynamicRange < 40.0 || lowEnergyRatio > 0.2;
}

// 打印音频分析结果
void analyzeAudio(const std::string& name, const AudioData& data) {
    std::cout << "\n分析音频: " << name << "\n";
    std::cout << "================================\n";

    clock_t start = clock();
    bool interruption = detectInterruption(data);
    bool echo = detectEcho(data);
    bool choppiness = detectChoppiness(data);
    bool noise = detectNoise(data);
    clock_t end = clock();

    std::cout << "中断检测: " << (interruption ? "存在" : "无") << "\n";
    std::cout << "回声检测: " << (echo ? "存在" : "无") << "\n";
    std::cout << "断续检测: " << (choppiness ? "存在" : "无") << "\n";
    std::cout << "杂音检测: " << (noise ? "存在" : "无") << "\n";

    if (!(interruption || echo || choppiness || noise)) {
        std::cout << "音频质量正常\n";
    }

    double elapsed = static_cast<double>(end - start) / CLOCKS_PER_SEC;
    std::cout << "分析耗时: " << elapsed << " 秒\n";
    std::cout << "================================\n";
}

int main() {
    std::srand(std::time(0));

    // 创建测试音频
    AudioData normalAudio(NUM_SAMPLES, 0);
    AudioData interruptionAudio(NUM_SAMPLES, 0);
    AudioData echoAudio(NUM_SAMPLES, 0);
    AudioData choppyAudio(NUM_SAMPLES, 0);
    AudioData noisyAudio(NUM_SAMPLES, 0);

    // 生成正常音频 (扫频信号)
    generateSweep(normalAudio);

    // 生成中断音频 (正常音频 + 中断)
    interruptionAudio = normalAudio;
    addInterruption(interruptionAudio, NUM_SAMPLES/2, SAMPLE_RATE); // 1秒中断

    // 生成回声音频 (正常音频 + 回声)
    echoAudio = normalAudio;
    addEcho(echoAudio, SAMPLE_RATE/8, 0.6); // 125ms延迟，衰减0.6

    // 生成断续音频 (正常音频 + 断续)
    choppyAudio = normalAudio;
    addChoppiness(choppyAudio, 160); // 10ms静音段

    // 生成杂音音频 (正常音频 + 背景噪声)
    noisyAudio = normalAudio;
    addNoise(noisyAudio, 0.08); // 8%幅度的噪声

    // 保存音频文件
    saveAsWav("normal.wav", normalAudio);
    saveAsWav("interruption.wav", interruptionAudio);
    saveAsWav("echo.wav", echoAudio);
    saveAsWav("choppy.wav", choppyAudio);
    saveAsWav("noisy.wav", noisyAudio);

    std::cout << "已生成测试音频文件:\n";
    std::cout << " - normal.wav (正常音频)\n";
    std::cout << " - interruption.wav (中断音频)\n";
    std::cout << " - echo.wav (回声音频)\n";
    std::cout << " - choppy.wav (断续音频)\n";
    std::cout << " - noisy.wav (杂音音频)\n";

    // 分析音频
    analyzeAudio("正常音频", normalAudio);
    analyzeAudio("中断音频", interruptionAudio);
    analyzeAudio("回声音频", echoAudio);
    analyzeAudio("断续音频", choppyAudio);
    analyzeAudio("杂音音频", noisyAudio);

    return 0;
}

#endif

#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
#include <algorithm>
#include <random>
#include <climits>
#include <ctime>
#include <map>
#include <sstream>
#include <portaudio.h> // 用于实时音频处理

// 音频参数
const int SAMPLE_RATE = 24000;   // 16kHz
const int BIT_DEPTH = 16;        // 16-bit
const int DURATION = 31;         // 10秒
const int NUM_SAMPLES = SAMPLE_RATE * DURATION;
const int CHUNK_SIZE = 1024;     // 每次处理的音频块大小 (64ms)

// 音频数据容器
using AudioData = std::vector<int16_t>;

// 配置参数结构体
struct Config {
    // 中断检测参数
    double interruption_threshold = 0.01;
    int interruption_window = 512;   // 32ms
    int interruption_silence_threshold = 10; // 连续静音窗口数

    // 回声检测参数
    double echo_threshold = 0.15;
    int echo_window = 1024;          // 64ms
    int echo_min_delay = 100;        // 6.25ms
    int echo_max_delay = 2000;       // 125ms

    // 断续检测参数
    double choppiness_threshold = 0.1;
    int choppiness_window = 160;     // 10ms
    double choppiness_energy_threshold = 0.02;

    // 杂音检测参数
    double noise_dynamic_range = 40.0;
    double noise_low_energy_ratio = 0.2;
    int noise_energy_window = 512;   // 32ms

    // 实时处理参数
    int realtime_buffer_size = 2048; // 128ms缓冲区
    int realtime_min_duration = 200; // 最小分析时长(ms)
};

// 全局配置对象
Config globalConfig;

// 配置文件解析
bool parseConfig(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        std::cerr << "无法打开配置文件: " << filename << std::endl;
        return false;
    }

    std::map<std::string, double> configMap;
    std::string line;
    while (std::getline(file, line)) {
        // 跳过注释行和空行
        if (line.empty() || line[0] == '#') continue;

        // 解析键值对
        std::istringstream iss(line);
        std::string key;
        if (std::getline(iss, key, '=')) {
            double value;
            if (iss >> value) {
                configMap[key] = value;
            }
        }
    }

    // 应用配置参数
    if (configMap.find("interruption_threshold") != configMap.end())
        globalConfig.interruption_threshold = configMap["interruption_threshold"];
    if (configMap.find("interruption_window") != configMap.end())
        globalConfig.interruption_window = configMap["interruption_window"];
    if (configMap.find("interruption_silence_threshold") != configMap.end())
        globalConfig.interruption_silence_threshold = configMap["interruption_silence_threshold"];

    if (configMap.find("echo_threshold") != configMap.end())
        globalConfig.echo_threshold = configMap["echo_threshold"];
    if (configMap.find("echo_window") != configMap.end())
        globalConfig.echo_window = configMap["echo_window"];
    if (configMap.find("echo_min_delay") != configMap.end())
        globalConfig.echo_min_delay = configMap["echo_min_delay"];
    if (configMap.find("echo_max_delay") != configMap.end())
        globalConfig.echo_max_delay = configMap["echo_max_delay"];

    if (configMap.find("choppiness_threshold") != configMap.end())
        globalConfig.choppiness_threshold = configMap["choppiness_threshold"];
    if (configMap.find("choppiness_window") != configMap.end())
        globalConfig.choppiness_window = configMap["choppiness_window"];
    if (configMap.find("choppiness_energy_threshold") != configMap.end())
        globalConfig.choppiness_energy_threshold = configMap["choppiness_energy_threshold"];

    if (configMap.find("noise_dynamic_range") != configMap.end())
        globalConfig.noise_dynamic_range = configMap["noise_dynamic_range"];
    if (configMap.find("noise_low_energy_ratio") != configMap.end())
        globalConfig.noise_low_energy_ratio = configMap["noise_low_energy_ratio"];
    if (configMap.find("noise_energy_window") != configMap.end())
        globalConfig.noise_energy_window = configMap["noise_energy_window"];

    if (configMap.find("realtime_buffer_size") != configMap.end())
        globalConfig.realtime_buffer_size = configMap["realtime_buffer_size"];
    if (configMap.find("realtime_min_duration") != configMap.end())
        globalConfig.realtime_min_duration = configMap["realtime_min_duration"];

    std::cout << "配置文件加载成功: " << filename << std::endl;
    return true;
}

// 生成基本正弦波
void generateSineWave(AudioData& data, double freq, double amplitude = 0.8) {
    for (int i = 0; i < data.size(); i++) {
        double t = static_cast<double>(i) / SAMPLE_RATE;
        double value = amplitude * (1 << (BIT_DEPTH - 1)) * std::sin(2.0 * M_PI * freq * t);
        data[i] = static_cast<int16_t>(value);
    }
}

// 生成扫频信号 (20Hz - 8kHz)
void generateSweep(AudioData& data) {
    const double startFreq = 20.0;
    const double endFreq = 8000.0;

    for (int i = 0; i < data.size(); i++) {
        double t = static_cast<double>(i) / SAMPLE_RATE;
        double freq = startFreq + (endFreq - startFreq) * (t / DURATION);
        double value = 0.8 * (1 << (BIT_DEPTH - 1)) * std::sin(2.0 * M_PI * freq * t);
        data[i] = static_cast<int16_t>(value);
    }
}

// 添加中断 (静音段)
void addInterruption(AudioData& data, int startSample, int durationSamples) {
    std::fill(data.begin() + startSample,
              data.begin() + startSample + durationSamples, 0);
}

// 添加回声
void addEcho(AudioData& data, int delaySamples, double decay) {
    for (int i = data.size() - 1; i >= delaySamples; i--) {
        double value = data[i] + decay * data[i - delaySamples];

        // 防止溢出
        if (value > SHRT_MAX) value = SHRT_MAX;
        else if (value < SHRT_MIN) value = SHRT_MIN;

        data[i] = static_cast<int16_t>(value);
    }
}

// 添加断续 (随机静音段)
void addChoppiness(AudioData& data, int segmentLength = 80) {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<int> dist(0, data.size() - segmentLength);

    // 添加10个静音段
    for (int i = 0; i < 10; i++) {
        int pos = dist(gen);
        std::fill(data.begin() + pos, data.begin() + pos + segmentLength, 0);
    }
}

// 添加杂音 (随机噪声)
void addNoise(AudioData& data, double noiseLevel) {
    std::random_device rd;
    std::mt19937 gen(rd());
    int16_t maxNoise = static_cast<int16_t>(noiseLevel * (1 << (BIT_DEPTH - 1)));
    std::uniform_int_distribution<int16_t> dist(-maxNoise, maxNoise);

    for (int i = 0; i < data.size(); i++) {
        int32_t value = static_cast<int32_t>(data[i]) + dist(gen);

        // 防止溢出
        if (value > SHRT_MAX) value = SHRT_MAX;
        else if (value < SHRT_MIN) value = SHRT_MIN;

        data[i] = static_cast<int16_t>(value);
    }
}

// 保存为WAV文件
void saveAsWav(const std::string& filename, const AudioData& data) {
    std::ofstream file(filename, std::ios::binary);

    // WAV文件头
    struct WavHeader {
        char riff[4] = {'R', 'I', 'F', 'F'};
        uint32_t chunkSize;
        char wave[4] = {'W', 'A', 'V', 'E'};
        char fmt[4] = {'f', 'm', 't', ' '};
        uint32_t fmtSize = 16;
        uint16_t audioFormat = 1; // PCM
        uint16_t numChannels = 1;
        uint32_t sampleRate;
        uint32_t byteRate;
        uint16_t blockAlign;
        uint16_t bitsPerSample;
        char data[4] = {'d', 'a', 't', 'a'};
        uint32_t dataSize;
    };

    WavHeader header;
    header.chunkSize = 36 + data.size() * sizeof(int16_t);
    header.sampleRate = SAMPLE_RATE;
    header.byteRate = SAMPLE_RATE * sizeof(int16_t);
    header.blockAlign = sizeof(int16_t);
    header.bitsPerSample = BIT_DEPTH;
    header.dataSize = data.size() * sizeof(int16_t);

    file.write(reinterpret_cast<const char*>(&header), sizeof(header));
    file.write(reinterpret_cast<const char*>(data.data()), data.size() * sizeof(int16_t));
}

// 计算信号能量
double calculateEnergy(const AudioData& data, int start, int end) {
    double energy = 0.0;
    int count = 0;
    for (int i = start; i < end && i < static_cast<int>(data.size()); i++) {
        double sample = static_cast<double>(data[i]) / (1 << (BIT_DEPTH - 1));
        energy += sample * sample;
        count++;
    }
    return count > 0 ? energy / count : 0.0;
}

// 检测中断 (静音段)
bool detectInterruption(const AudioData& data) {
    int windowSize = globalConfig.interruption_window;
    int silenceThreshold = globalConfig.interruption_silence_threshold;
    double threshold = globalConfig.interruption_threshold;

    int silentWindows = 0;
    for (int i = 0; i < static_cast<int>(data.size()); i += windowSize) {
        double energy = calculateEnergy(data, i, i + windowSize);

        if (energy < threshold) {
            silentWindows++;
            if (silentWindows >= silenceThreshold) {
                return true;
            }
        } else {
            silentWindows = 0;
        }
    }
    return false;
}

// 检测回声 (使用自相关)
bool detectEcho(const AudioData& data) {
    int windowSize = globalConfig.echo_window;
    int minDelay = globalConfig.echo_min_delay;
    int maxDelay = globalConfig.echo_max_delay;
    double threshold = globalConfig.echo_threshold;

    // 选择分析区域（避免扫频信号变化过快的区域）
    int start = SAMPLE_RATE * 2; // 2秒处开始
    int end = std::min(start + windowSize * 10, static_cast<int>(data.size()) - maxDelay);

    for (; start < end; start += windowSize) {
        // 计算自相关
        std::vector<double> correlations(maxDelay - minDelay, 0.0);
        for (int delay = minDelay; delay < maxDelay; delay++) {
            double sum = 0.0;
            int count = 0;

            for (int i = start; i < start + windowSize; i++) {
                double sample1 = static_cast<double>(data[i]) / (1 << (BIT_DEPTH - 1));
                double sample2 = static_cast<double>(data[i + delay]) / (1 << (BIT_DEPTH - 1));
                sum += sample1 * sample2;
                count++;
            }

            if (count > 0) {
                correlations[delay - minDelay] = sum / count;
            }
        }

        // 寻找显著峰值
        double maxCorr = *std::max_element(correlations.begin(), correlations.end());
        if (maxCorr > threshold) {
            // 检查峰值是否明显高于平均值
            double sum = std::accumulate(correlations.begin(), correlations.end(), 0.0);
            double avg = sum / correlations.size();

            if (maxCorr > 3.0 * avg) {
                return true;
            }
        }
    }
    return false;
}

// 检测断续
bool detectChoppiness(const AudioData& data) {
    int windowSize = globalConfig.choppiness_window;
    double threshold = globalConfig.choppiness_threshold;
    double energyThreshold = globalConfig.choppiness_energy_threshold;

    int silentCount = 0;
    int totalWindows = 0;

    for (int i = 0; i < static_cast<int>(data.size()); i += windowSize) {
        double energy = calculateEnergy(data, i, i + windowSize);

        if (energy < energyThreshold) {
            silentCount++;
        }
        totalWindows++;
    }

    double silentRatio = static_cast<double>(silentCount) / totalWindows;
    return silentRatio > threshold;
}

// 检测杂音
bool detectNoise(const AudioData& data) {
    int windowSize = globalConfig.noise_energy_window;
    double dynamicRangeThreshold = globalConfig.noise_dynamic_range;
    double lowEnergyRatioThreshold = globalConfig.noise_low_energy_ratio;

    // 计算整体信噪比
    double totalEnergy = 0.0;
    double minEnergy = 1.0;
    double maxEnergy = 0.0;

    std::vector<double> energies;

    for (int i = 0; i < static_cast<int>(data.size()); i += windowSize) {
        double energy = calculateEnergy(data, i, i + windowSize);
        energies.push_back(energy);
        totalEnergy += energy;

        if (energy < minEnergy) minEnergy = energy;
        if (energy > maxEnergy) maxEnergy = energy;
    }

    // 计算动态范围
    double dynamicRange = 10 * log10(maxEnergy / (minEnergy + 1e-10));

    // 计算低能量窗口比例
    double lowEnergyCount = 0;
    double lowEnergyThreshold = totalEnergy / energies.size() * 0.1; // 平均能量的10%
    for (double e : energies) {
        if (e < lowEnergyThreshold) {
            lowEnergyCount++;
        }
    }
    double lowEnergyRatio = lowEnergyCount / energies.size();

    // 动态范围 < 阈值 或 低能量窗口占比 > 阈值 视为有杂音
    return dynamicRange < dynamicRangeThreshold || lowEnergyRatio > lowEnergyRatioThreshold;
}

// 实时音频分析类
class RealTimeAudioAnalyzer {
private:
    AudioData buffer;
    size_t bufferSize;
    int minDuration;
    bool isAnalyzing;

public:
    RealTimeAudioAnalyzer() : bufferSize(globalConfig.realtime_buffer_size),
                              minDuration(globalConfig.realtime_min_duration),
                              isAnalyzing(false) {
        buffer.reserve(bufferSize * 2); // 预分配空间
    }

    // 添加音频数据块
    void addAudioData(const int16_t* data, size_t numSamples) {
        // 添加新数据
        buffer.insert(buffer.end(), data, data + numSamples);

        // 保持缓冲区大小
        if (buffer.size() > bufferSize) {
            buffer.erase(buffer.begin(), buffer.begin() + (buffer.size() - bufferSize));
        }

        // 当有足够数据时开始分析
        if (!isAnalyzing && buffer.size() >= minDuration * SAMPLE_RATE / 1000) {
            isAnalyzing = true;
            analyzeCurrentBuffer();
            isAnalyzing = false;
        }
    }

    // 分析当前缓冲区
    void analyzeCurrentBuffer() {
        // 计算分析时长(ms)
        double durationMs = buffer.size() * 1000.0 / SAMPLE_RATE;

        std::cout << "\n[实时分析] 音频时长: " << durationMs << " ms" << std::endl;

        // 执行检测
        bool interruption = detectInterruption(buffer);
        bool echo = detectEcho(buffer);
        bool choppiness = detectChoppiness(buffer);
        bool noise = detectNoise(buffer);

        // 输出结果
        if (interruption) std::cout << "  - 检测到音频中断!" << std::endl;
        if (echo) std::cout << "  - 检测到回声!" << std::endl;
        if (choppiness) std::cout << "  - 检测到音频断续!" << std::endl;
        if (noise) std::cout << "  - 检测到背景杂音!" << std::endl;

        if (!(interruption || echo || choppiness || noise)) {
            std::cout << "  - 音频质量正常" << std::endl;
        }
    }

    // 重置缓冲区
    void reset() {
        buffer.clear();
    }
};

// 实时音频回调函数
static int audioCallback(const void* inputBuffer, void* outputBuffer,
                         unsigned long framesPerBuffer,
                         const PaStreamCallbackTimeInfo* timeInfo,
                         PaStreamCallbackFlags statusFlags,
                         void* userData) {
    RealTimeAudioAnalyzer* analyzer = static_cast<RealTimeAudioAnalyzer*>(userData);
    const int16_t* in = static_cast<const int16_t*>(inputBuffer);

    (void)outputBuffer; // 防止未使用变量警告

    // 将音频数据传递给分析器
    analyzer->addAudioData(in, framesPerBuffer);

    return paContinue;
}

// 初始化PortAudio
bool initPortAudio(PaStream*& stream, RealTimeAudioAnalyzer* analyzer) {
    PaError err = Pa_Initialize();
    if (err != paNoError) {
        std::cerr << "PortAudio初始化失败: " << Pa_GetErrorText(err) << std::endl;
        return false;
    }

    // 设置输入参数
    PaStreamParameters inputParameters;
    inputParameters.device = Pa_GetDefaultInputDevice();
    if (inputParameters.device == paNoDevice) {
        std::cerr << "未找到默认输入设备" << std::endl;
        return false;
    }

    inputParameters.channelCount = 1; // 单声道
    inputParameters.sampleFormat = paInt16;
    inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;
    inputParameters.hostApiSpecificStreamInfo = nullptr;

    // 打开音频流
    err = Pa_OpenStream(&stream, &inputParameters, nullptr, SAMPLE_RATE,
                        CHUNK_SIZE, paClipOff, audioCallback, analyzer);
    if (err != paNoError) {
        std::cerr << "无法打开音频流: " << Pa_GetErrorText(err) << std::endl;
        return false;
    }

    // 启动音频流
    err = Pa_StartStream(stream);
    if (err != paNoError) {
        std::cerr << "无法启动音频流: " << Pa_GetErrorText(err) << std::endl;
        return false;
    }

    std::cout << "音频输入已启动，按Enter键停止..." << std::endl;
    return true;
}

// 打印音频分析结果
void analyzeAudio(const std::string& name, const AudioData& data) {
    std::cout << "\n分析音频: " << name << "\n";
    std::cout << "================================\n";

    clock_t start = clock();
    bool interruption = detectInterruption(data);
    bool echo = detectEcho(data);
    bool choppiness = detectChoppiness(data);
    bool noise = detectNoise(data);
    clock_t end = clock();

    std::cout << "中断检测: " << (interruption ? "存在" : "无") << "\n";
    std::cout << "回声检测: " << (echo ? "存在" : "无") << "\n";
    std::cout << "断续检测: " << (choppiness ? "存在" : "无") << "\n";
    std::cout << "杂音检测: " << (noise ? "存在" : "无") << "\n";

    if (!(interruption || echo || choppiness || noise)) {
        std::cout << "音频质量正常\n";
    }

    double elapsed = static_cast<double>(end - start) / CLOCKS_PER_SEC;
    std::cout << "分析耗时: " << elapsed << " 秒\n";
    std::cout << "================================\n";
}

int main(int argc, char* argv[]) {
    // 加载配置文件
    std::string configFile = R"(/root/audio_test.cfg)";
    if (argc > 1) {
        configFile = argv[1];
    }

    if (!parseConfig(configFile)) {
        std::cout << "使用默认配置参数" << std::endl;
    }

    // 创建测试音频
//    AudioData normalAudio(NUM_SAMPLES, 0);
//    AudioData interruptionAudio(NUM_SAMPLES, 0);
//    AudioData echoAudio(NUM_SAMPLES, 0);
//    AudioData choppyAudio(NUM_SAMPLES, 0);
//    AudioData noisyAudio(NUM_SAMPLES, 0);

//    // 生成正常音频 (扫频信号)
//    generateSweep(normalAudio);

//    // 生成中断音频 (正常音频 + 中断)
//    interruptionAudio = normalAudio;
//    addInterruption(interruptionAudio, NUM_SAMPLES/2, SAMPLE_RATE); // 1秒中断

//    // 生成回声音频 (正常音频 + 回声)
//    echoAudio = normalAudio;
//    addEcho(echoAudio, SAMPLE_RATE/8, 0.6); // 125ms延迟，衰减0.6

//    // 生成断续音频 (正常音频 + 断续)
//    choppyAudio = normalAudio;
//    addChoppiness(choppyAudio, 160); // 10ms静音段

//    // 生成杂音音频 (正常音频 + 背景噪声)
//    noisyAudio = normalAudio;
//    addNoise(noisyAudio, 0.08); // 8%幅度的噪声

//    // 保存音频文件
//    saveAsWav("normal.wav", normalAudio);
//    saveAsWav("interruption.wav", interruptionAudio);
//    saveAsWav("echo.wav", echoAudio);
//    saveAsWav("choppy.wav", choppyAudio);
//    saveAsWav("noisy.wav", noisyAudio);

    std::cout << "已生成测试音频文件:\n";
    std::cout << " - normal.wav (正常音频)\n";
    std::cout << " - interruption.wav (中断音频)\n";
    std::cout << " - echo.wav (回声音频)\n";
    std::cout << " - choppy.wav (断续音频)\n";
    std::cout << " - noisy.wav (杂音音频)\n";

    // 分析音频
//    analyzeAudio("正常音频", normalAudio);
//    analyzeAudio("中断音频", interruptionAudio);
//    analyzeAudio("回声音频", echoAudio);
//    analyzeAudio("断续音频", choppyAudio);
//    analyzeAudio("杂音音频", noisyAudio);
    const char* filename = R"(/root/humanVoice.pcm)";
    FILE* fp = fopen(filename, "rb");
    if (!fp) {
        std::cerr << "无法打开文件: " << filename << std::endl;
        return -2;
    }

    // 获取文件大小
    fseek(fp, 0, SEEK_END);
    long fileSize = ftell(fp);
    rewind(fp);

    std::cout << "文件大小: " << fileSize << " 字节" << std::endl;

    // 读取 PCM 数据
    std::vector<int16_t> buffer(fileSize / sizeof(int16_t));
    size_t readCount = fread(buffer.data(), sizeof(int16_t), buffer.size(), fp);
    fclose(fp);

    if (readCount != buffer.size()) {
        std::cerr << "读取数据异常，实际读取样本数: " << readCount << std::endl;
        return 1;
    }

    std::cout << "读取样本数: " << readCount << std::endl;

    // 构造 AudioData
    AudioData audioData;
    audioData.swap(buffer);

    // 调用分析函数
    analyzeAudio("Root目录 PCM 文件", audioData);

    // 实时音频分析
    RealTimeAudioAnalyzer analyzer;
    PaStream* stream = nullptr;

    if (initPortAudio(stream, &analyzer)) {
        // 等待用户输入停止
        std::cin.get();

        // 停止并关闭音频流
        Pa_StopStream(stream);
        Pa_CloseStream(stream);
        Pa_Terminate();
    }

    return 0;
}

#if 0
#include <iostream>
#include <mpg123.h>
#include <vector>

int main(int argc, char* argv[]) {

    const char* mp3File = R"(/root/humanVoice.mp3)";

    // 初始化 mpg123
    mpg123_init();
    mpg123_handle *mh = mpg123_new(NULL, NULL);
    mpg123_open(mh, mp3File);

    // 设置输出格式
    long rate;
    int channels, encoding;
    mpg123_getformat(mh, &rate, &channels, &encoding);

    // 分配缓冲区
    const int buffer_size = 8192;
    unsigned char buffer[buffer_size];
    size_t done;

    std::vector<int16_t> pcm_data;
    //pcm_data.reserve(100);

    // 解码 MP3 为 PCM（int16格式）
    while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK) {
        int samples = done / sizeof(int16_t);
        int16_t* samples16 = reinterpret_cast<int16_t*>(buffer);
        pcm_data.insert(pcm_data.end(), samples16, samples16 + samples);
    }

    // 清理
    mpg123_close(mh);
    mpg123_delete(mh);
    mpg123_exit();

    // 输出信息
    std::cout << "Decoded PCM samples: " << pcm_data.size() << std::endl;
    std::cout << "Sample rate: " << rate << ", Channels: " << channels << std::endl;

    // 可将 pcm_data 保存为 .pcm 或 .wav 文件
    FILE* fout = fopen(R"(/root/humanVoice.pcm)", "wb");
    fwrite(pcm_data.data(), sizeof(int16_t), pcm_data.size(), fout);
    fclose(fout);
    return 0;
}
#endif
